package com.hjl.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hjl.utils.JwtHelper;
import com.hjl.utils.Result;
import com.hjl.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author ServivE
 * @version 0.1
 * @className LoginProtectedInterceptor
 * @description 登录保护拦截器，检查token是否过期
 * @date 2024/8/23 20:05
 * @since jdk17
 */
@Component//将下面的类放到容器中 方便后面直接取用
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //检查是否有效
        boolean expiration = jwtHelper.isExpiration(token);
        //有效放行  没有过期
        if (!expiration) {
            return true;
        }
        //无效返回504状态json
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        //result对象变成json写回
            //1.result转为json字符串=========》ObjectMapper对象映射类：java对象转为json字符串 || json字符串转为java对象
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);//将result对象写成json字符串

        //用字符输入流将json写出
        response.getWriter().print(json);
        return false;
    }


}
